#!/usr/bin/env bash

set -o errexit
set -o nounset
set -o pipefail

REPO_ROOT="$(git rev-parse --show-toplevel)"
SRC_DIR=${REPO_ROOT}/
cd "${SRC_DIR}"

if [[ -z "${IMAGE_PREFIX:-}" ]]; then
  IMAGE_PREFIX=""
fi
echo "Building images with prefix ${IMAGE_PREFIX}"

if [[ -z "${TAG:-}" ]]; then
  TAG=latest
fi

if [[ -z "${BUILDX_ARGS:-}" ]]; then
  BUILDX_ARGS="--load"
fi
if [[ -z "${DOCKER:-}" ]]; then
  DOCKER="docker"
fi
echo "Using container tool: ${DOCKER}"

if [[ "${DOCKER}" == "podman" ]]; then
  # Podman doesn't support buildx, use regular build command
  if [[ "${BUILDX_ARGS}" == "--push" ]]; then
    # For podman, build and then push separately
    echo "Building with podman..."
    ${DOCKER} build \
        --platform linux/amd64 \
        -f images/kubectl-ai/Dockerfile \
        -t ${IMAGE_PREFIX}kubectl-ai:${TAG} \
        .
    echo "Pushing with podman..."
    ${DOCKER} push ${IMAGE_PREFIX}kubectl-ai:${TAG}
  else
    # For --load or other args, just build
    ${DOCKER} build \
        --platform linux/amd64 \
        -f images/kubectl-ai/Dockerfile \
        -t ${IMAGE_PREFIX}kubectl-ai:${TAG} \
        .
  fi
else
  # Use docker buildx for docker
  # Specify platform to avoid multi-arch build requirements
  ${DOCKER} buildx build ${BUILDX_ARGS} \
      --platform linux/amd64 \
      -f images/kubectl-ai/Dockerfile \
      -t ${IMAGE_PREFIX}kubectl-ai:${TAG} \
      --progress=plain .
fi
